import React, { Component } from 'react'
import MyNavBar from '../../components/MyNavBar'
import { getCityList, getHotCityList } from '../../api/city'
import { getCurrentCity, setLocalCity } from '../../utils/city'
import { AutoSizer, List } from 'react-virtualized'
import { Toast } from 'antd-mobile'
import styles from './index.module.scss'
const TITLE_HEIGHT = 36
const CITY_HEIGHT = 50
const HASDATA = ['北京', '上海', '广州', '深圳']
export default class CityList extends Component {
    constructor() {
        super()
        this.state = {
            cityListObj: null, // 左边的城市列表对象
            cityIndexList: null, // 右边的城市索引数组
            selectedIndex: 0 // 选中的索引
        }
    }
    componentDidMount() {
        this.dealWithCityListData()
    }
    dealWithCityListData = async () => {
        // 处理a-z的数据
        const res1 = await getCityList()
        // console.log(res1.data)
        const tempObj = {}
        let tempIndexList = []
        res1.data.body.forEach(item => {
            // 把遍历到的那项的首字母取出来
            const letter = item.short.substr(0, 1)
            // console.log(letter)
            // 判断该字母的属性是否在tempObj中有值
            if (tempObj[letter]) {
                tempObj[letter].push(item)
            } else {
                tempObj[letter] = [item]
            }
        })

        tempIndexList = Object.keys(tempObj).sort()
        // 处理热门城市数据
        const res2 = await getHotCityList()
        console.log('res2:', res2.data)
        tempObj['hot'] = res2.data.body
        tempIndexList.unshift('hot')
        // console.log(tempObj)
        // console.log(tempIndexList)
        // 处理当前定位城市
        const res3 = await getCurrentCity()
        console.log(res3)
        tempObj['#'] = [res3]
        tempIndexList.unshift('#')
        // console.log(tempObj)
        // console.log(tempIndexList)
        this.setState({
            cityListObj: tempObj,
            cityIndexList: tempIndexList
        })
    }
    // 格式化标题
    formatTitle = letter => {
        switch (letter) {
            case '#':

                return '定位城市';
            case 'hot':

                return '热门城市';
            default:
                return letter.toUpperCase();
        }
    }
    listRef = React.createRef()
    // 切换右边的索引
    toggleSelect = (index) => {
        // console.log(index)
        this.listRef.current.scrollToRow(index)
    }
    // 切换城市的渲染
    toggleCitySelect = ({ label, value }) => {
        console.log(label, value)
        if (!HASDATA.includes(label)) {
            Toast.info('该城市暂无房源~', 1.5)
            return
        }
        // 保存到本地
        setLocalCity({ label, value })
        // 关闭当前页面
        this.props.history.goBack()
    }
    // 左侧城市列表
    rowRenderer = ({
        key, // Unique key within array of rows
        index, // Index of row within collection
        isScrolling, // The List is currently being scrolled
        isVisible, // This row is visible within the List (eg it is not an overscanned row)
        style // Style object to be applied to row (to position it)
    }) => {
        const { cityListObj, cityIndexList } = this.state
        const letter = cityIndexList[index]
        const list = cityListObj[letter]
        return (
            <div className={styles.city} style={style} key={key} >
                <div className={styles.title}>{this.formatTitle(letter)}</div>
                {list.map(item => {
                    return (
                        <div onClick={() => this.toggleCitySelect(item)} key={item.value} className={styles.name}>
                            {item.label}
                        </div>
                    )
                })}
            </div>
        )
    }
    // 计算高度
    calcRowHeight = ({ index }) => {
        const { cityIndexList, cityListObj } = this.state
        const letter = cityIndexList[index]
        const list = cityListObj[letter]
        return TITLE_HEIGHT + list.length * CITY_HEIGHT
    }
    // 右侧索引列表
    renderCityIndexList = () => {
        const { cityIndexList, selectedIndex } = this.state
        return (
            <div className={styles.cityIndex}>
                {cityIndexList.map((item, index) => {
                    return (<div onClick={() => this.toggleSelect(index)} className={styles.cityIndexItem} key={item}>
                        <span className={selectedIndex === index ? styles.indexActive : ''}>{item === 'hot' ? '热' : item.toUpperCase()}</span>
                    </div>)
                })}
            </div>
        )
    }
    // 滑动左侧改变右侧索引
    onRowsRendered = ({ startIndex }) => {
        // console.log('startIndex', startIndex)
        if (startIndex !== this.state.selectedIndex) {
            this.setState({
                selectedIndex: startIndex
            })
        }
    }
    render() {
        const { cityIndexList } = this.state
        return (
            <div className={styles.citylist}>
                {/* <MyNavBar history={this.props.history}>城市选择</MyNavBar> */}
                <MyNavBar>城市选择</MyNavBar>
                {/* 渲染左侧列表 */}
                {cityIndexList && (
                    <AutoSizer>{
                        ({ width, height }) => (
                            <List
                                ref={this.listRef}
                                width={width}
                                height={height - 45}
                                rowCount={cityIndexList.length}
                                rowHeight={this.calcRowHeight}
                                rowRenderer={this.rowRenderer}
                                onRowsRendered={this.onRowsRendered}
                                scrollToAlignment="start" // 默认auto，对其方式
                            />)
                    }</AutoSizer>
                )}
                {/* 渲染右侧列表 */}
                {cityIndexList && this.renderCityIndexList()}
            </div>
        )
    }
}
